<template>
  <div class="write-article">
    <HeaderComponent 
      :isLoggedIn="isLoggedIn" 
      :userInfo="userInfo" 
      :showUserPanel="showUserPanel"
      @open-login="$emit('open-login')"
      @toggle-user-panel="$emit('toggle-user-panel')"
      @logout="$emit('logout')"
    />
    
    <div class="write-container">
      <div class="write-header">
        <h1>写文章</h1>
        <div class="write-actions">
          <button class="btn btn-secondary" @click="saveDraft" :disabled="isPublishing">保存草稿</button>
          <button class="btn btn-primary" @click="publishArticle" :disabled="isPublishing">
            {{ isPublishing ? '发布中...' : '发布文章' }}
          </button>
        </div>
      </div>
      
      <div class="write-form">
        <div class="title-input">
          <input 
            type="text" 
            placeholder="输入文章标题..." 
            v-model="articleTitle"
            class="title-field"
            :class="{ error: errors.title }"
          />
          <div v-if="errors.title" class="error-message">{{ errors.title }}</div>
        </div>
        
        <div class="editor-toolbar">
          <div class="toolbar-group">
            <button class="toolbar-btn" title="加粗"><strong>B</strong></button>
            <button class="toolbar-btn" title="斜体"><em>I</em></button>
            <button class="toolbar-btn" title="下划线"><u>U</u></button>
            <button class="toolbar-btn" title="删除线"><s>S</s></button>
          </div>
          <div class="toolbar-group">
            <button class="toolbar-btn" title="标题">H</button>
            <button class="toolbar-btn" title="引用">"</button>
            <button class="toolbar-btn" title="代码">{ }</button>
            <button class="toolbar-btn" title="链接">🔗</button>
          </div>
          <div class="toolbar-group">
            <button class="toolbar-btn" title="图片">📷</button>
            <button class="toolbar-btn" title="表格">📊</button>
            <button class="toolbar-btn" title="列表">📝</button>
          </div>
        </div>
        
        <div class="editor-container">
          <textarea 
            v-model="articleContent"
            placeholder="开始写作...支持 Markdown 语法"
            class="content-editor"
            :class="{ error: errors.content }"
          ></textarea>
          
          <div class="preview-panel" v-if="showPreview">
            <div class="preview-content" v-html="previewContent"></div>
          </div>
        </div>
        
        <div v-if="errors.content" class="error-message">{{ errors.content }}</div>
        
        <div class="editor-footer">
          <div class="word-count">
            字数: {{ wordCount }}
          </div>
          <div class="editor-controls">
            <button 
              class="preview-toggle" 
              @click="togglePreview"
              :class="{ active: showPreview }"
            >
              {{ showPreview ? '隐藏预览' : '显示预览' }}
            </button>
          </div>
        </div>
      </div>
      
      <div class="article-settings">
        <div class="settings-section">
          <h3>文章设置</h3>
          <div class="setting-item">
            <label>分类 <span class="required">*</span></label>
            <select 
              v-model="selectedCategoryId"
              @change="onCategoryChange"
              class="setting-select"
              :class="{ error: errors.category }"
            >
              <option value="">请选择分类</option>
              <option 
                v-for="category in categories" 
                :key="category.id" 
                :value="category.id"
              >
                {{ category.name }}
              </option>
            </select>
            <div v-if="errors.category" class="error-message">{{ errors.category }}</div>
          </div>
          <div class="setting-item">
            <label>标签</label>
            <input 
              type="text" 
              placeholder="添加标签，用逗号分隔"
              v-model="articleTags"
              @input="onTagsChange"
              class="setting-input"
            />
            <div class="tag-suggestions" v-if="tags.length > 0">
              <span class="suggestion-label">可选标签：</span>
              <span 
                v-for="tag in tags.slice(0, 10)" 
                :key="tag.id" 
                class="tag-suggestion"
                @click="addTag(tag.name)"
              >
                {{ tag.name }}
              </span>
            </div>
          </div>
          <div class="setting-item">
            <label>文章摘要</label>
            <textarea 
              v-model="articleSummary"
              placeholder="输入文章摘要（可选，不填写将自动截取文章开头）"
              class="setting-textarea"
              rows="3"
            ></textarea>
          </div>
          <div class="setting-item">
            <label>封面图</label>
            <div class="cover-upload">
              <input 
                type="url" 
                v-model="coverImage"
                placeholder="输入封面图片URL"
                class="setting-input cover-input"
                :class="{ error: errors.coverImage }"
              />
              <span class="upload-tip">建议尺寸: 900x500</span>
              <div v-if="errors.coverImage" class="error-message">{{ errors.coverImage }}</div>
            </div>
          </div>
          <div class="setting-item">
            <label>文章设置</label>
            <div class="setting-checkboxes">
              <label class="checkbox-item">
                <input type="checkbox" v-model="isOriginal" />
                <span class="checkbox-label">原创文章</span>
              </label>
              <label class="checkbox-item">
                <input type="checkbox" v-model="allowComment" />
                <span class="checkbox-label">允许评论</span>
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 发布成功弹窗 -->
    <div v-if="showSuccessModal" class="success-modal-overlay" @click="closeSuccessModal">
      <div class="success-modal" @click.stop>
        <div class="success-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" fill="#52c41a"/>
            <path d="M9 12l2 2 4-4" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h2 class="success-title">太好啦，你发布成功了！</h2>
        <p class="success-message">你的文章已经成功发布，读者们很快就能看到你的精彩内容了。</p>
        <div class="success-actions">
          <button class="btn btn-secondary" @click="writeAnother">再写一篇</button>
          <button class="btn btn-primary" @click="goToHome">回到首页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import HeaderComponent from '@/components/HeaderComponent.vue'
import { categoryAPI, tagAPI, articleAPI } from '@/api/index.js'

export default {
  name: 'WriteArticle',
  components: {
    HeaderComponent
  },
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default: () => ({})
    },
    showUserPanel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 文章基本信息
      articleTitle: '',
      articleContent: '',
      articleSummary: '',
      coverImage: '',
      
      // 分类和标签
      articleCategory: '',
      selectedCategoryId: null,
      articleTags: '',
      selectedTagIds: [],
      
      // 设置选项
      isOriginal: true,
      allowComment: true,
      
      // UI状态
      showPreview: false,
      isPublishing: false,
      showSuccessModal: false,
      
      // 数据列表
      categories: [],
      tags: [],
      
      // 错误信息
      errors: {}
    }
  },
  computed: {
    wordCount() {
      return this.articleContent.length
    },
    previewContent() {
      // 简单的 Markdown 预览（实际项目中建议使用专业的 Markdown 解析库）
      return this.articleContent
        .replace(/\n/g, '<br>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
    }
  },
  async mounted() {
    await this.loadCategories();
    await this.loadTags();
    
    // 检查是否有本地草稿
    const draftData = localStorage.getItem('article_draft');
    if (draftData) {
      this.$confirm('检测到本地草稿，是否加载？', '提示', {
        confirmButtonText: '加载草稿',
        cancelButtonText: '忽略',
        type: 'info'
      }).then(() => {
        this.loadDraft();
      }).catch(() => {
        // 用户选择忽略草稿
      });
    }
  },
  methods: {
    // 加载分类列表
    async loadCategories() {
      try {
        const response = await categoryAPI.getList()
        if (response.code === 0) {
          this.categories = response.data || []
        }
      } catch (error) {
        console.error('加载分类失败:', error)
        this.$message?.error('加载分类失败')
      }
    },
    
    // 加载标签列表
    async loadTags() {
      try {
        const response = await tagAPI.getList()
        if (response.code === 0) {
          this.tags = response.data || []
        }
      } catch (error) {
        console.error('加载标签失败:', error)
        this.$message?.error('加载标签失败')
      }
    },
    
    // 切换预览
    togglePreview() {
      this.showPreview = !this.showPreview
    },
    
    // 处理分类选择
    onCategoryChange() {
      // selectedCategoryId 已经通过 v-model 绑定，无需额外处理
      console.log('选择的分类ID:', this.selectedCategoryId);
    },
    
    // 处理标签选择
     onTagsChange() {
       // 将逗号分隔的标签字符串转换为标签ID数组
       if (this.articleTags) {
         const tagNames = this.articleTags.split(',').map(tag => tag.trim()).filter(tag => tag)
         this.selectedTagIds = []
         
         tagNames.forEach(tagName => {
           const tag = this.tags.find(t => t.name === tagName)
           if (tag) {
             this.selectedTagIds.push(tag.id)
           }
         })
       } else {
         this.selectedTagIds = []
       }
     },
     
     // 添加标签
     addTag(tagName) {
       if (!this.articleTags) {
         this.articleTags = tagName
       } else {
         const currentTags = this.articleTags.split(',').map(tag => tag.trim())
         if (!currentTags.includes(tagName)) {
           this.articleTags += ', ' + tagName
         }
       }
       this.onTagsChange()
     },
    
    // 表单验证
    validateForm() {
      this.errors = {};
      
      // 验证标题
      if (!this.articleTitle.trim()) {
        this.errors.title = '请输入文章标题';
      } else if (this.articleTitle.trim().length < 5) {
        this.errors.title = '文章标题至少需要5个字符';
      } else if (this.articleTitle.trim().length > 100) {
        this.errors.title = '文章标题不能超过100个字符';
      }
      
      // 验证内容
      if (!this.articleContent.trim()) {
        this.errors.content = '请输入文章内容';
      } else if (this.articleContent.trim().length < 50) {
        this.errors.content = '文章内容至少需要50个字符';
      }
      
      // 验证分类
      if (!this.selectedCategoryId) {
        this.errors.category = '请选择文章分类';
      }
      
      // 封面图片URL不做格式限制，用户可以输入任何内容
      
      return Object.keys(this.errors).length === 0;
    },
    
    // 发布文章
    async publishArticle() {
      if (!this.validateForm()) {
        // 滚动到第一个错误字段
        this.$nextTick(() => {
          const errorElement = this.$el.querySelector('.error');
          if (errorElement) {
            errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        });
        this.$message?.error('请完善文章信息')
        return
      }
      
      this.isPublishing = true
      
      try {
        // 处理标签
        this.onTagsChange()
        
        // 构建请求数据
        const articleData = {
          title: this.articleTitle.trim(),
          content: this.articleContent.trim(),
          categoryId: this.selectedCategoryId,
          tagIds: this.selectedTagIds,
          summary: this.articleSummary.trim() || this.articleContent.substring(0, 200) + '...',
          coverImage: this.coverImage || '',
          isOriginal: this.isOriginal,
          allowComment: this.allowComment
        }
        
        const response = await articleAPI.write(articleData)
        
        if (response.code === 0) {
          // 显示成功弹窗
          this.showSuccessModal = true;
        } else {
          this.$message({
            type: 'error',
            message: '发布失败：' + (response.message || '未知错误')
          });
        }
      } catch (error) {
        console.error('发布文章失败:', error)
        let errorMessage = '发布失败，请稍后重试';
        
        if (error.response) {
          // 服务器返回错误状态码
          if (error.response.status === 401) {
            errorMessage = '请先登录';
          } else if (error.response.status === 403) {
            errorMessage = '没有权限发布文章';
          } else if (error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message;
          }
        } else if (error.message) {
          errorMessage = error.message;
        }
        
        this.$message({
          type: 'error',
          message: errorMessage
        });
      } finally {
        this.isPublishing = false
      }
    },
    
    // 保存草稿
    async saveDraft() {
      try {
        const draftData = {
          title: this.articleTitle,
          content: this.articleContent,
          categoryId: this.selectedCategoryId,
          tagIds: this.selectedTagIds,
          summary: this.articleSummary,
          coverImage: this.coverImage,
          isOriginal: this.isOriginal,
          allowComment: this.allowComment,
          savedAt: new Date().toISOString()
        };
        
        // 保存到本地存储
        localStorage.setItem('article_draft', JSON.stringify(draftData));
        
        this.$message({
          type: 'success',
          message: '草稿已保存到本地'
        });
      } catch (error) {
        console.error('保存草稿失败:', error);
        this.$message({
          type: 'error',
          message: '保存草稿失败'
        });
      }
    },
    
    // 加载草稿
    loadDraft() {
      try {
        const draftData = localStorage.getItem('article_draft');
        if (draftData) {
          const draft = JSON.parse(draftData);
          this.articleTitle = draft.title || '';
          this.articleContent = draft.content || '';
          this.selectedCategoryId = draft.categoryId || '';
          this.selectedTagIds = draft.tagIds || [];
          this.articleSummary = draft.summary || '';
          this.coverImage = draft.coverImage || '';
          this.isOriginal = draft.isOriginal !== undefined ? draft.isOriginal : true;
          this.allowComment = draft.allowComment !== undefined ? draft.allowComment : true;
          
          this.$message({
            type: 'info',
            message: '已加载本地草稿'
          });
        }
      } catch (error) {
        console.error('加载草稿失败:', error);
      }
    },
    
    // 清除草稿
    clearDraft() {
      localStorage.removeItem('article_draft');
    },
    
    // 重置表单
    resetForm() {
      this.articleTitle = ''
      this.articleContent = ''
      this.articleSummary = ''
      this.coverImage = ''
      this.articleCategory = ''
      this.selectedCategoryId = null
      this.articleTags = ''
      this.selectedTagIds = []
      this.isOriginal = true
      this.allowComment = true
      this.errors = {}
      
      // 清除本地草稿
      this.clearDraft()
    },
    
    // 关闭成功弹窗
    closeSuccessModal() {
      this.showSuccessModal = false;
    },
    
    // 再写一篇
    writeAnother() {
      this.showSuccessModal = false;
      this.resetForm();
      // 滚动到页面顶部
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    
    // 回到首页
    goToHome() {
      this.showSuccessModal = false;
      // 这里需要根据你的路由配置来跳转到首页
      // 假设首页路由是 '/' 或 '/home'
      this.$router.push('/');
    }
  },
  emits: ['open-login', 'toggle-user-panel', 'logout']
}
</script>

<style scoped>
.write-article {
  min-height: 100vh;
  background-color: #f4f5f5;
}

.write-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.write-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e6eb;
}

.write-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}

.write-actions {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-secondary {
  background: #f2f3f5;
  color: #515767;
}

.btn-secondary:hover {
  background: #e4e6eb;
}

.btn-primary {
  background: #1e80ff;
  color: white;
}

.btn-primary:hover {
  background: #0969da;
}

.write-form {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.title-input {
  margin-bottom: 20px;
}

.title-field {
  width: 100%;
  padding: 16px;
  border: 1px solid #e4e6eb;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 500;
  outline: none;
  transition: border-color 0.2s ease;
}

.title-field:focus {
  border-color: #1e80ff;
}

.title-field.error {
  border-color: #f56565;
}

.editor-toolbar {
  display: flex;
  gap: 16px;
  padding: 12px 16px;
  background: #f8f9fa;
  border: 1px solid #e4e6eb;
  border-bottom: none;
  border-radius: 6px 6px 0 0;
}

.toolbar-group {
  display: flex;
  gap: 8px;
}

.toolbar-btn {
  padding: 6px 10px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #515767;
  transition: background-color 0.2s ease;
}

.toolbar-btn:hover {
  background: #e4e6eb;
}

.editor-container {
  display: flex;
  min-height: 400px;
}

.content-editor {
  flex: 1;
  padding: 16px;
  border: 1px solid #e4e6eb;
  border-top: none;
  border-radius: 0 0 6px 6px;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
  outline: none;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  transition: border-color 0.2s ease;
}

.content-editor:focus {
  border-color: #1e80ff;
}

.content-editor.error {
  border-color: #f56565;
}

.preview-panel {
  flex: 1;
  border: 1px solid #e4e6eb;
  border-left: none;
  border-top: none;
  border-radius: 0 0 6px 0;
  background: white;
}

.preview-content {
  padding: 16px;
  font-size: 14px;
  line-height: 1.6;
  color: #1d2129;
}

.editor-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e6eb;
}

.word-count {
  font-size: 12px;
  color: #86909c;
}

.preview-toggle {
  padding: 6px 12px;
  border: 1px solid #e4e6eb;
  background: white;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.preview-toggle:hover {
  border-color: #1e80ff;
  color: #1e80ff;
}

.preview-toggle.active {
  background: #1e80ff;
  color: white;
  border-color: #1e80ff;
}

.article-settings {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.settings-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.setting-item {
  margin-bottom: 16px;
}

.setting-item label {
  display: block;
  margin-bottom: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
}

.setting-select,
.setting-input,
.setting-textarea {
  width: 100%;
  max-width: 300px;
  padding: 8px 12px;
  border: 1px solid #e4e6eb;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s ease;
}

.setting-select:focus,
.setting-input:focus,
.setting-textarea:focus {
  border-color: #1e80ff;
}

.setting-select.error,
.setting-input.error,
.setting-textarea.error {
  border-color: #f56565;
}

.setting-textarea {
  resize: vertical;
  font-family: inherit;
}

.required {
  color: #f56565;
}

.error-message {
  color: #f56565;
  font-size: 12px;
  margin-top: 4px;
}

.cover-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}

.upload-btn {
  padding: 8px 16px;
  border: 1px solid #e4e6eb;
  background: white;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-btn:hover {
  border-color: #1e80ff;
  color: #1e80ff;
}

.upload-tip {
  font-size: 12px;
  color: #86909c;
}

.cover-input {
  margin-bottom: 8px;
}

.tag-suggestions {
  margin-top: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e4e6eb;
}

.suggestion-label {
  font-size: 12px;
  color: #86909c;
  margin-right: 8px;
}

.tag-suggestion {
  display: inline-block;
  padding: 2px 8px;
  margin: 2px 4px 2px 0;
  background: #e4e6eb;
  border-radius: 12px;
  font-size: 12px;
  color: #515767;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tag-suggestion:hover {
  background: #d4e3fd;
  color: #1e80ff;
}

.setting-checkboxes {
  display: flex;
  gap: 16px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.checkbox-item input[type="checkbox"] {
  margin: 0;
}

.checkbox-label {
  font-size: 14px;
  color: #515767;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 成功弹窗样式 */
.success-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.success-modal {
  background: white;
  border-radius: 12px;
  padding: 40px;
  max-width: 480px;
  width: 90%;
  text-align: center;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  animation: slideUp 0.3s ease;
}

.success-icon {
  margin-bottom: 24px;
  display: flex;
  justify-content: center;
}

.success-title {
  margin: 0 0 16px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
}

.success-message {
  margin: 0 0 32px 0;
  font-size: 16px;
  color: #515767;
  line-height: 1.5;
}

.success-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.success-actions .btn {
  padding: 12px 24px;
  font-size: 16px;
  min-width: 120px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>